package biz

import (
	"context"

	"github.com/go-kratos/kratos/v2/metadata"
	"github.com/google/wire"
)

// ProviderSet is biz providers.
var ProviderSet = wire.NewSet()

type Result[T any] struct {
	Code    int
	Message string
	Data    T
}

type Meta struct {
	TraceId  string
	Caller   string
	Target   string
	Deadline string
}

func (m *Meta) Set(ctx context.Context) context.Context {
	if m.TraceId != "" {
		ctx = metadata.AppendToClientContext(ctx, "TraceId", m.TraceId)
	}

	if m.Caller != "" {
		ctx = metadata.AppendToClientContext(ctx, "Caller", m.Caller)
	}

	if m.Target != "" {
		ctx = metadata.AppendToClientContext(ctx, "Target", m.Target)
	}

	if m.Deadline != "" {
		ctx = metadata.AppendToClientContext(ctx, "Deadline", m.Deadline)
	}
	return ctx
}

func (m *Meta) Get(ctx context.Context) {
	if md, ok := metadata.FromClientContext(ctx); ok {
		m.Caller = md.Get("Caller")
		m.TraceId = md.Get("TraceId")
		m.Target = md.Get("Target")
		m.Deadline = md.Get("Deadline")
	}
}

func GetMetaData(ctx context.Context) map[string]string {
	var meta = &Meta{}
	meta.Get(ctx)
	var result = map[string]string{
		"Caller":   meta.Caller,
		"TraceId":  meta.TraceId,
		"Target":   meta.Target,
		"Deadline": meta.Deadline,
	}
	return result
}
